package com.javaketang.dky.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaketang.dky.entity.EasybuyProduct;
import com.javaketang.dky.entity.EasybuyProductCategory;
import com.javaketang.dky.mapper.EasybuyProductCategoryMapper;
import com.javaketang.dky.mapper.EasybuyProductMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dky
 * @since 2021-07-06
 */
@Controller
@RequestMapping("easybuy")
public class EasybuyProductController {

    @Resource
    private EasybuyProductMapper productMapper;
    @Resource
    private EasybuyProductCategoryMapper categoryMapper;

    /**
     * 查询分类管理
     *
     * @param current
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/products")
    public String products(Integer current, HttpSession session, Model model) {

        session.setAttribute("action", "product");
        //分页
        Page<EasybuyProduct> page = new Page<>(current == null ? 1 : current, 10);

        //查询分类管理
        IPage<EasybuyProduct> iPage = productMapper.selectPage(page, new QueryWrapper<EasybuyProduct>().eq("isDelete", 0));

        List<EasybuyProduct> list = iPage.getRecords();

        //获取总页数
        int sumDateNumber = (int) (page.getTotal() % 10 == 0 ? page.getTotal() / 10 : page.getTotal() / 10 + 1);
        model.addAttribute("lists", list);
        model.addAttribute("sumPage", sumDateNumber);
        model.addAttribute("current", current == null ? 1 : current);

        return "Member_User";
    }

    /**
     * 删除商品
     *
     * @return
     */
    @RequestMapping("/deleteById")
    @ResponseBody
    public Map<String, Object> deleteById(Integer id) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //创建商品对象
        EasybuyProduct product = new EasybuyProduct();
        product.setId(id);
        product.setIsDelete(1);

        int row = productMapper.updateById(product);

        //判断删除成功
        if (row > 0) {

            map.put("message", "删除成功");
            map.put("status", 1);
        } else {
            map.put("message", "删除失败，服务器内部错误！");
            map.put("status", 0);
        }


        return map;
    }

    /**
     * 商品上架和修改商品
     *
     * @param id
     * @return
     */
    @RequestMapping("/putaway")
    public String putaway(Integer id, HttpSession session, Model model) {

        session.setAttribute("action", "putaway");

        //查询已经分类
        List<EasybuyProductCategory> list = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().eq("type", 1));

        //判断是添加商品
        if (id == null) {

            session.setAttribute("sold", "add");

            //修改商品
        } else {

            //根据id查询
            EasybuyProduct product = productMapper.selectById(id);

            List<EasybuyProductCategory> list2 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().eq("type", 2));
            List<EasybuyProductCategory> list3 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().eq("type", 3));

            model.addAttribute("product", product);
            model.addAttribute("list2", list2);
            model.addAttribute("list3", list3);


            session.setAttribute("sold", "update");

        }

        model.addAttribute("lists", list);

        return "Member_User";
    }

    /**
     * 商品上架
     *
     * @param product
     * @param file
     * @return
     */
    @RequestMapping("/productPutaway")
    public String productPutaway(EasybuyProduct product, @RequestParam("photo") MultipartFile file, HttpSession session, HttpServletRequest request) throws IOException {


        System.out.println("对象：" + product);

        if (file.isEmpty()) {


            if (product.getId() != 0) {
                //修改方法
                int row = productMapper.updateById(product);

                //判断添加成功时
                if (row > 0) {

                    System.out.println("修改成功！");
                    return "forward:products";
                }
            }

            System.out.println("文件未上传");
        } else {
            System.out.println("文件长度：" + file.getSize());
            System.out.println("文件类型：" + file.getContentType());
            System.out.println("文件原名：" + file.getOriginalFilename());

            //获取文件原名
            String uploadFileName = file.getOriginalFilename();

            //截取后缀名
            String extentdName = uploadFileName.substring(uploadFileName.indexOf(".") + 1, uploadFileName.length());

            //把文件重命名，防止出现重复，文件名称中文乱码
            String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();

            //拼接后的文件名
            String fileName = uuid + "." + extentdName;

            System.out.println("文件名：" + fileName);

//            获取设置上传文件的目标位置
//            String realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\resources";

            //获取设置上传文件的目标位置
            String realPath = "F:\\resources";

            System.out.println("目标位置：" + realPath);

            //获取tomcat 路径
            String path = request.getContextPath().replaceAll("/", "");

            System.out.println("上下文路径--》" + path + "/webapps");

            //判断路径是否存在
            File file1 = new File(realPath);

            //如果目录不存在就创建目录
            if (!file1.exists()) {

                //创建目录
                file1.mkdirs();
            }

            //上传到指定位置
            file.transferTo(new File(file1, fileName));

            //赋值文件名
            product.setFileName(fileName);

            //判断是添加时
            if (product.getId() == 0) {

                //添加
                int row = productMapper.insert(product);

                //判断添加成功时
                if (row > 0) {

                    System.out.println("添加成功！");
                    return "forward:products";
                }

                //修改时
            } else {

                //修改方法
                int row = productMapper.updateById(product);

                //判断添加成功时
                if (row > 0) {

                    System.out.println("修改成功！");
                    return "forward:products";
                }


            }


        }
        session.setAttribute("action", "putaway");
        session.setAttribute("sold", "add");
        return "Member_User";
    }

}

